from readlater.config import ConfigManager
from readlater.utils.logger import get_logger
from readlater.utils.url_extractor import extract_urls
from readlater.database import DatabaseManager

import requests
import datetime
import hashlib
import sqlite3



class ChatlogManager:
    def __init__(self):
        self.logger = get_logger(__name__)
        self.config = ConfigManager("./config/config.yaml")
        self.db_manager = DatabaseManager(self.config.get_database_path())

    def read_today_articles(self, target_talker: str=None):
        return self.read_articles(target_talker=target_talker, search_time=datetime.date.today().strftime("%Y-%m-%d"))
        

    def read_articles(self, target_talker: str = None, search_time: str = None):
        # 从配置文件获取默认参数和第三方API配置
        talker = target_talker if target_talker else self.config.get(
            "wechat.target_user")
        time_period = int(self.config.get("wechat.time_period"))
        api_url = self.config.get("chatlog_api.url") + '/api/v1/chatlog'
        timeout = self.config.get("chatlog_api.timeout", 30)

        # 获取当前日期
        time = search_time
        if time is None:
            time_end = datetime.date.today()
            formatted_time_end = time_end.strftime("%Y-%m-%d")
            time = f"{formatted_time_end}"

            if time_period != 0:
                time_start = time_end - datetime.timedelta(days=time_period)
                formatted_time_start = time_start.strftime("%Y-%m-%d")
                time = f"{formatted_time_start}~{formatted_time_end}"

        # 构建请求参数
        params = {
            "talker": talker,
            "time": time,
            "format": "json"
        }
        self.logger.info(f"请求参数:{api_url}, params: {params}")

        # 设置请求头
        headers = {
            "Content-Type": "application/json"
        }

        try:
            response = requests.get(
                api_url,
                params=params,
                headers=headers,
                timeout=timeout
            )
            self.logger.info(f"响应: {response.text}")

            # 检查响应状态
            if response.status_code != 200:
                raise requests.HTTPError(
                    f"第三方API请求失败: {response.text}", 
                    response=response
                )

            # 获取响应数据
            chatlogs = response.json()
            self.logger.info(f"获取到 {len(chatlogs)} 条聊天记录")

            articles = []
            for chatlog in chatlogs:
                # 使用get方法安全访问字典键，避免KeyError
                if chatlog.get('type') == 49 and chatlog.get('subType') == 5:
                    # 先检查contents是否存在且是字典类型
                    contents = chatlog.get('contents', {})
                    if isinstance(contents, dict):
                        title = contents.get('title', '无标题')
                        url = contents.get('url', '')
                        if url:
                            articles.append({
                                "title": title,
                                "url": url,
                                "id": hashlib.md5(url.encode()).hexdigest()
                            })
                        else:
                            self.logger.info(f"获取到无效URL的聊天记录: {chatlog}")
                    else:
                        self.logger.info(f"聊天记录contents格式无效: {chatlog}")
                elif chatlog.get('type') == 1 and chatlog.get('subType') == 0:
                    content = chatlog.get('content', "")
                    if isinstance(content, str):
                        urls = extract_urls(content)
                        if len(urls) > 0:
                            for url in urls:
                                articles.append({
                                    "title": content,
                                    "url": url,
                                    "id": hashlib.md5(url.encode()).hexdigest()
                                })

            # 根据格式返回结果
            self.logger.info(f"获取到 {len(articles)} 条文章")
            return articles
        except requests.RequestException as e:
            raise HTTPException(
                status_code=500,
                detail=f"请求失败: {str(e)}"
            )


    def save_articles(self, articles: list):
        """
        将文章列表保存到todo_list表中

        Args:
            articles (list): 文章列表，每个文章包含title、url、id等字段
        """
        success = 0
        failed = 0
        duplicated = 0
        if not articles or not isinstance(articles, list):
            self.logger.warning("无效的文章列表，无需保存")
            return True,success,failed,duplicated

        # 创建数据库管理器实例
        try:
            # 连接数据库
            if not self.db_manager.connect():
                self.logger.error("数据库连接失败，无法保存文章")
                return False

            # 开始事务
            self.db_manager.begin_transaction()

            # 批量插入文章
            for article in articles:
                # 检查文章数据是否完整
                if not all(key in article for key in ['id', 'url', 'title']):
                    self.logger.warning(f"文章数据不完整，跳过: {article}")
                    continue

                # 准备插入数据
                article_id = article['id']
                url = article['url']
                title = article['title']
                status = DatabaseManager.STATUS_LINK_EXTRACTED  # 默认初始状态

                # 插入或更新文章
                try:
                    # 先检查是否已存在
                    article = self.db_manager.get_article_by_id(article_id)

                    if article:
                        # # 更新现有记录
                        # self.db_manager.cursor.execute(
                        #     "UPDATE todo_list SET title = ?, url = ?, status = ?, datetime = ? WHERE id = ?",
                        #     (title, url, status, current_time, article_id)
                        # )
                        self.logger.debug(f"文章已存在，跳过处理: {article_id} - {title}")
                        duplicated += 1
                    else:
                        # 插入新记录
                        if self.db_manager.insert_article(article_id=article_id, url=url, title=title, status=status):
                            self.logger.debug(f"插入文章成功: {article_id}")
                            success += 1
                        else:
                            self.logger.error(f"插入文章失败: {article_id}")
                            failed += 1

                except sqlite3.Error as e:
                    self.logger.error(f"保存文章失败: {str(e)}, 文章数据: {article}")
                    # 回滚事务
                    self.db_manager.rollback()
                    failed += 1

            # 提交事务
            self.db_manager.commit()
            self.logger.info(f"成功保存 {success} 篇文章到数据库, 失败 {failed} 篇, 重复 {duplicated} 篇")

            return True,success,failed,duplicated
        except Exception as e:
            self.logger.error(f"保存文章时发生错误: {str(e)}")
            # 回滚事务
            if self.db_manager.conn:
                self.db_manager.rollback()
            return False,success,failed,duplicated
        finally:
            # 关闭数据库连接
            self.db_manager.close()
